<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="工序">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序"
            clearable
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processList"
              :key="item.id"
              :label="item.processCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品型号">
          <el-select
            v-model="searchParam.partCode"
            placeholder="请选择产品型号"
            clearable
            filterable
            :filter-method="customFilter"
          >
            <el-option
              v-for="item in filteredOptions"
              :key="item.productCode"
              :label="item.productCode"
              :value="item.productCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检具名称">
          <el-select
            v-model="searchParam.detectionEquipCode"
            placeholder="请选择检具名称"
            clearable
            filterable
          >
            <el-option
              v-for="item in gageEquipList"
              :key="item.toolCode"
              :label="item.toolName"
              :value="item.toolCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="searchParam.workOrderStatus"
            placeholder="请选择工单状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('PsmOrderStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="变更时间">
          <el-date-picker
            v-model="searchParam.changeTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getchangeTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="工单状态"
          prop="workOrderStatus"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              useDictionary("PsmOrderStatus", scope.row.workOrderStatus) || ""
            }}
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          label="工单类型"-->
<!--          prop="orderType"-->
<!--          min-width="150"-->
<!--          show-overflow-tooltip-->
<!--          align="center"-->
<!--        />-->
        <el-table-column
          label="变更时间"
          prop="changeTime"
          min-width="150"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="工序"
          prop="processCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
<!--        <el-table-column-->
<!--          label="工单编号"-->
<!--          prop="orderNo"-->
<!--          min-width="170"-->
<!--          show-overflow-tooltip-->
<!--          align="center"-->
<!--        />-->
        <el-table-column
          label="产品型号"
          prop="partCode"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="检具编号"
          prop="detectionEquipCode"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="检具名称"
          prop="detectionEquipName"
          min-width="130"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="特性编号"
          prop="paramCode"
          min-width="90"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="特性描述"
          prop="paramName"
          min-width="140"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="处理"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
              >
                <i-ep-edit />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <qdproductfeatureorder-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :orderTypes="props.orderTypes"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import {
  getMdminspectiontoolApi,
  getMdmprocessListApi,
  getMdmproductinfosApi,
  getMdmproductinfosApi1,
} from "@/utils/commonData";
import _ from "lodash-es";
import SearchFormGroup from "@/views/pcm/pcmMonitoring/components/SearchFormGroup.vue";

defineOptions({
  name: "PCMQDPRODUCTFEATUREORDER",
  inheritAttrs: false,
});

const props = defineProps({
  orderTypes: {
    type: Array,
    default: ["featureOrder"],
  },
});

// 请求参数
const requestApi = "/dmpDosPcm/qdproductfeatureorder/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  processId: "",
  partCode: "",
  detectionEquipCode: "",
  workOrderStatus: "",
  changeTimeSearch: [],
  changeTimeStart: "",
  changeTimeEnd: "",
  orderTypes: props.orderTypes
};

const deleteParam = {
  api: "/dmpDosPcm/qdproductfeatureorder/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getProcessList();
  getProductList();
  // // 获取量检具列表
  getGageEquipList({});
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/qdproductfeatureorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开产品特性工单表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改产品特性工单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增产品特性工单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开产品特性工单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "产品特性工单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getchangeTime(data: any) {
  if (data) {
    searchParam.value.changeTimeStart = data[0];
    searchParam.value.changeTimeEnd = data[1];
  } else {
    searchParam.value.changeTimeStart = "";
    searchParam.value.changeTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/dmpDosPcm/qdproductfeatureorder/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
// 获取工序列表
const processList = ref<any>([]);
async function getProcessList() {
  processList.value = (await getMdmprocessListApi({})) || [];
}
async function processChange(id: string) {
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
  } else {
    searchParam.value.processCode = "";
  }
}
// 获取产品型号列表
const productList = ref<any>([]);
const filteredOptions = ref<any>([]);
async function getProductList() {
  const list: any = (await getMdmproductinfosApi({})) || [];
  productList.value = list;
  filteredOptions.value = [...productList.value];
}

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...productList.value];
    return;
  }
  filteredOptions.value = productList.value.filter((option: any) =>
    option.productCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

// 获取量检具列表
const gageEquipList = ref<any>([]);

async function getGageEquipList(params) {
  gageEquipList.value = (await getMdminspectiontoolApi({})) || [];
}
</script>
